<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #container {
            border: 1px solid #000;
            position: relative;
            }
            
        #box {
            background-color: red;
            cursor: move;
        }
    </style>
</head>
<body>
    <div id="container" style="width: 300px; height: 300px; position: relative;">
        <div id="box" style="width: 50px; height: 50px; position: absolute; cursor: move;"></div>
    </div>
</body>
<script>
let dragging = false;
const container = document.getElementById('container');
const box = document.getElementById('box');
 
box.addEventListener('mousedown', function(e) {
  dragging = true;
  const offsetX = e.clientX - box.offsetLeft;
  const offsetY = e.clientY - box.offsetTop;
 
  function mouseMoveHandler(e) {
    if (dragging) {
      const x = e.clientX - offsetX;
      const y = e.clientY - offsetY;
 
      // 限制盒子不超出div
      if (x < 0) {
        box.style.left = '0px';
      } else if (x > container.offsetWidth - box.offsetWidth) {
        box.style.left = `${container.offsetWidth - box.offsetWidth}px`;
      } else {
        box.style.left = `${x}px`;
      }
 
      if (y < 0) {
        box.style.top = '0px';
      } else if (y > container.offsetHeight - box.offsetHeight) {
        box.style.top = `${container.offsetHeight - box.offsetHeight}px`;
      } else {
        box.style.top = `${y}px`;
      }
    }
  }
 
  document.addEventListener('mousemove', mouseMoveHandler);
  
  document.addEventListener('mouseup', function() {
    dragging = false;
    document.removeEventListener('mousemove', mouseMoveHandler);
  });
 
  box.addEventListener('mouseup', function() {
    dragging = false;
    document.removeEventListener('mousemove', mouseMoveHandler);
  });
});
</script>
</html>